//
//  QpSearchViewController.m
//  A_project
//
//  Created by Tiny on 16/2/25.
//  Copyright © 2016年 七平. All rights reserved.
//

#import "QpSearchViewController.h"
#import "QpSearchModel.h"
#import <MBProgressHUD.h>
@interface QpSearchViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>
{
    // HUD (Head-Up Display, 意思是抬头显示的意思)
    MBProgressHUD *HUD;
}
@property (nonatomic, retain) UISearchController *search;/**< 搜索控制视图 */
@property (nonatomic, copy) NSString *strHight;/**< 高亮用字符串 保存搜索信息 */
@property (nonatomic, retain) NSMutableArray *dataArr;/**< 接收数据数组 */
@property (nonatomic, retain) UITableView *tableView;/**< 显示数据内容 */

@end

@implementation QpSearchViewController

#pragma mark - 内存管理
- (void)dealloc
{
    [_search release];
    [_strHight release];
    [_dataArr release];
    [_tableView release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //    搜索步骤:
    //    1.初始化搜索视图
    //    2.搜索视图签订协议
    //    3.设置搜索视图
    //    4.在搜索视图的协议方法中 获取输入内容 对搜索内容解析数据 刷新tableView
    //    5.在tableVIewCell方法中设置高亮 NSMutableAttributedString
    
    
    // 初始化搜索视图
    self.search = [[UISearchController alloc]initWithSearchResultsController:nil];
    // 签订协议
//    _search.searchResultsUpdater = self;
    _search.searchBar.delegate = self;
    // 屏幕变灰 yes时tableview 不能下拉
    _search.dimsBackgroundDuringPresentation = NO;
    // 设置点击搜索框时 隐藏导航栏
    _search.hidesNavigationBarDuringPresentation = NO;
    // 占位符 默认search
    _search.searchBar.placeholder = @"搜索XXXXXXXXX";
    
    // 搜索栏的风格
    _search.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    // 把 搜索视图加到导航栏上
    self.navigationItem.titleView = _search.searchBar;
    // 释放
    [_search release];
    // 自适应
    [_search.searchBar sizeToFit];
    
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(left)]autorelease];
   
    // 创建tableview
    [self creatTableView];
}

- (void)left
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark -  创建tableview
- (void)creatTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView release];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
}
// 协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

#pragma mark - 实现搜索栏协议方法
// 知道搜索栏有内容 就执行下面的方法

//- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
//{
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    // 将搜索内容转化为字符串
    // 等同于 获取搜索的信息 显示的文本
    [self showTextDialog];
    self.strHight = [self.search.searchBar text];
//    BOOL t = [self stringContainsEmoji:_strHight];
//    BOOL w = [self isHaveIllegalChar:_strHight];
//    NSLog(@"%d",w);
//    if (t || w) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"没有您要搜索的内容" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [alert show];
//    }else
    if ([_strHight containsString:@" "]) {
        // 盘算如果有空格不执行
        // 没有则执行一下程序
        // 不写这个判断 打空格就会崩溃
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"没有您要搜索的内容" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        [HUD removeFromSuperview];
    }else{
        // 中文转码
        NSString *urlStr = [_strHight stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:_strHight]];
        
        // 变化的参数进行拼接
        NSString *str = [@"http://open.qyer.com/qyer/search/index?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&keyword=%E9%A6%99%E6%B8%AF&oauth_token=89dd34fbffaaa72503b4baa7a9d02812&page=1&place_field=country%7Ccity%7Cpoi&track_app_channel=App%2520Store&track_app_version=6.8.3&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=CDA3EEEB-61BF-473E-AFFF-32B6332C9BBF&track_os=ios%25207.1.2&track_user_id=7328550&type=place&v=1" stringByReplacingOccurrencesOfString:@"keyword=%E9%A6%99%E6%B8%AF" withString:[NSString stringWithFormat:@"keyword=%@", urlStr]];
        //http://open.qyer.com/qyer/search/index?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&keyword=%E5%9F%83%E6%96%AF%E5%85%8B%E5%B0%94&oauth_token=89dd34fbffaaa72503b4baa7a9d02812&page=1&place_field=country%7Ccity%7Cpoi&track_app_channel=App%2520Store&track_app_version=6.8.3&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=CDA3EEEB-61BF-473E-AFFF-32B6332C9BBF&track_os=ios%25207.1.2&track_user_id=7328550&type=place&v=1
        AFHTTPSessionManager *sessionManage = [AFHTTPSessionManager manager];
        [sessionManage GET:str parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            self.dataArr = [QpSearchModel modelHanderWithArray:responseObject[@"data"][@"entry"]];
            
            [_tableView reloadData];
            
            if (_dataArr.count == 0) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"没有您要搜索的内容" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alert show];

            }
            [HUD removeFromSuperview];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }
}

#pragma mark -  判断emoji表情
-(BOOL)stringContainsEmoji:(NSString *)string {
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     returnValue = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 returnValue = YES;
             }
             
         } else {
             // non surrogate
             if (0x2100 <= hs && hs <= 0x27ff) {
                 returnValue = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 returnValue = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 returnValue = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 returnValue = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                 returnValue = YES;
             }
         }
     }];
    
    return returnValue;
}
#pragma mark - 判断非法字符
- (BOOL)isHaveIllegalChar:(NSString *)str{
    NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"[]{}?!@（#%-*+=）/\\|~(＜＞$%^*)_+ "];
    NSRange range = [str rangeOfCharacterFromSet:doNotWant];
    return range.location<str.length;
}
// tableView cell 赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    QpSearchModel *qp = _dataArr[indexPath.row];
    NSMutableAttributedString *keyword = [[NSMutableAttributedString alloc]initWithString:qp.cnname];
    NSRange range = [qp.cnname rangeOfString:_strHight];
    [keyword setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName: [UIFont systemFontOfSize:20]} range:range];
    cell.textLabel.attributedText = keyword;
    
    return cell;
}
// 点击cell
//- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    //取消tableview 选中状态
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    QpSearchModel *s = _dataArr[indexPath.row];
//    if ([s.label isEqualToString:@"城市"]) {
//    QpCityDetailsViewController *qp = [QpCityDetailsViewController alloc];
//    qp.cityid = s.key;
//    [self.navigationController pushViewController:qp animated:YES];
//    }else if ([s.label isEqualToString:@"美食"]){
//        QpFoodDetailsSecondViewController *qp = [QpFoodDetailsSecondViewController alloc];
//        qp.cellid = s.key;
//        [self.navigationController pushViewController:qp animated:YES];
//    }
//}
#pragma mark - 菊花类
- (void)showTextDialog
{
    //初始化进度框，置于当前的View当中
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    
    //如果设置此属性则当前的view置于后台
    HUD.dimBackground = YES;
    
    //设置对话框文字
    HUD.labelText = @"请稍等";
    
    //显示对话框
    [HUD showAnimated:YES whileExecutingBlock:^{
        //对话框显示时需要执行的操作
        sleep(50);
    } completionBlock:^{
        //操作执行完后取消对话框
        [HUD removeFromSuperview];
        [HUD release];
        HUD = nil;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
